const fs = require('fs')
const path = require('path')

function shouldExclude(name, rules, type) {
    if (!rules || !rules.length) return false
    
    const typeRules = rules.filter(rule => rule.type === type)
    return typeRules.some(rule => {
        try {
            const regex = new RegExp(rule.pattern)
            return regex.test(name)
        } catch (e) {
            // 如果正则表达式无效，改为简单字符串匹配
            return name.includes(rule.pattern)
        }
    })
}

function scanDirectory(dirPath, filterRules) {
    const stats = fs.statSync(dirPath)
    if (!stats.isDirectory()) {
        throw new Error('Path is not a directory')
    }

    const result = {
        name: path.basename(dirPath),
        path: dirPath,
        type: 'directory',
        children: []
    }

    const items = fs.readdirSync(dirPath)

    for (const item of items) {
        const fullPath = path.join(dirPath, item)
        try {
            const itemStats = fs.statSync(fullPath)

            if (itemStats.isDirectory()) {
                if (shouldExclude(item, filterRules, 'folder')) {
                    continue
                }
                const childDir = scanDirectory(fullPath, filterRules)
                if (childDir.children.length > 0) {
                    result.children.push(childDir)
                }
            } else {
                if (shouldExclude(item, filterRules, 'file')) {
                    continue
                }
                result.children.push({
                    name: item,
                    path: fullPath,
                    type: 'file'
                })
            }
        } catch (e) {
            console.error(`Error reading ${fullPath}:`, e)
        }
    }

    return result
}

function copySelectedFiles(files, targetDir) {
    if (!fs.existsSync(targetDir)) {
        fs.mkdirSync(targetDir, { recursive: true })
    }

    const results = []

    for (const file of files) {
        try {
            const fileName = path.basename(file)
            const targetPath = path.join(targetDir, fileName)

            // 处理文件名冲突
            let finalTargetPath = targetPath
            let counter = 1
            while (fs.existsSync(finalTargetPath)) {
                const ext = path.extname(fileName)
                const name = path.basename(fileName, ext)
                finalTargetPath = path.join(targetDir, `${name}_${counter}${ext}`)
                counter++
            }

            fs.copyFileSync(file, finalTargetPath)
            results.push({
                source: file,
                target: finalTargetPath,
                success: true
            })
        } catch (e) {
            results.push({
                source: file,
                error: e.message,
                success: false
            })
        }
    }

    return results
}

module.exports = {
    scanDirectory,
    copySelectedFiles
}